package cwy.flylab.widget.util;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

/**
 * @author caowy
 */
public class ViewComboClick {

	public static final long DEFAULT_TIME = 2000;

	public static interface ComboClickListener {
		void onComboSuccess();
	}

	private class ClickItem {
		View view;
		int count;
		int current;
		long time;
		long lastClickTime;
	}

	private Context mContext;
	private final List<ClickItem> mClickItems;
	private ClickItem mCurrentItem;
	private ComboClickListener mComboClickListener;

	public ViewComboClick(Context context) {
		mContext = context;
		mClickItems = new ArrayList<ViewComboClick.ClickItem>();
	}

	public void setComboClickListener(ComboClickListener l) {
		this.mComboClickListener = l;
	}

	public ViewComboClick addItem(View view, int count) {
		return addItem(view, count, DEFAULT_TIME);
	}

	public ViewComboClick addItem(View view, int count, long time) {
		ClickItem clickItem = new ClickItem();
		clickItem.view = view;
		clickItem.count = count;
		clickItem.time = time;
		view.setOnTouchListener(new TouchListener(mContext, clickItem));
		mClickItems.add(clickItem);
		return this;
	}

	private void onItemClicked(ClickItem item) {
		final long curTime = System.currentTimeMillis();
		final long deltaTime = item.lastClickTime != 0L ? curTime - item.lastClickTime : 0L;
		if (item == mCurrentItem && deltaTime <= item.time) {
			item.current++;
			if (item.current == item.count) {
				int index = mClickItems.indexOf(item);
				if (index == mClickItems.size() - 1) {// 条件达成
					performComboClick();
					reset();
				} else {
					mCurrentItem = mClickItems.get(index + 1);
				}
			}
		} else {
			reset();
		}
	}

	private void reset() {
		mCurrentItem = mClickItems.get(0);
		for (ClickItem item : mClickItems) {
			item.current = 0;
			item.lastClickTime = 0L;
		}
	}

	private void performComboClick() {
		mComboClickListener.onComboSuccess();
	}

	private class TouchListener implements OnTouchListener {
		GestureDetector gestureDetector;
		ClickItem item;

		public TouchListener(Context context, ClickItem item) {
			this.item = item;
			gestureDetector = new GestureDetector(context, new ClickListener());
		}

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			boolean clicked = gestureDetector.onTouchEvent(event);
			if (clicked) {
				onItemClicked(item);
			}
			return false;
		}

	}

	private class ClickListener extends GestureDetector.SimpleOnGestureListener {

		public ClickListener() {
		}

		@Override
		public boolean onSingleTapConfirmed(MotionEvent e) {
			return true;
		}
	}
}
